package server

import (
	"os"
	"slices"

	"gitee.com/mkwchecking/k-scaffold/cmd/internal/flags"
	"gitee.com/mkwchecking/k-scaffold/cmd/internal/plugin"
	"gitee.com/mkwchecking/k-scaffold/config"
	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/spf13/cobra"
)

var ServerCmd = &cobra.Command{
	Use:   "server",
	Short: "Start the server",
	RunE:  runServer,
}

func runServer(cmd *cobra.Command, args []string) error {

	// Get the plugin
	plugin, err := plugin.NewPlugins(cmd)
	if err != nil {
		return err
	}

	// Get the server list
	srvTypes, err := cmd.Flags().GetStringArray(flags.FlagServerTypes.Name)
	if err != nil {
		return err
	}

	appSrvs := make([]transport.Server, 0)

	if slices.Contains(srvTypes, "http") {
		httpTrans, err := plugin.GetHttpServer()
		if err != nil {
			return err
		}
		appSrvs = append(appSrvs, httpTrans)
	}

	if slices.Contains(srvTypes, "grpc") {
		grpcTrans, err := plugin.GetGrpc()
		if err != nil {
			return err
		}
		appSrvs = append(appSrvs, grpcTrans)
	}

	app := kratos.New(
		kratos.ID(config.Get().App.Host.String()),
		kratos.Version(config.Get().App.Version),
		kratos.Signal(os.Interrupt),
		kratos.Context(plugin.Ctx()),
		kratos.Name(config.Get().App.Name),
		kratos.Server(appSrvs...),
	)

	return app.Run()
}
